package com.qf.bank.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.bank.common.Const;
import com.qf.bank.dao.AccountMapper;
import com.qf.bank.entity.Account;
import com.qf.bank.response.R;
import com.qf.bank.response.RCodes;
import com.qf.bank.service.IAccountService;
import com.qf.bank.utils.TokenUtils;
import com.qf.bank.vo.input.UpdatePasswordInputVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-12-03
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public R doLogin(HttpServletRequest request, Account account) {
        Account user = accountMapper.selectOne(
                new QueryWrapper<Account>()
                        .eq("cardno", account.getCardno())
                        .eq("password", account.getPassword())
        );
        if (user == null) {
            return R.createFAIL("用户名或密码错误");
        }
        if (!user.getStatus()) {
            return R.createFAIL(RCodes.FREEZE.getMsg());
        }

        String jwt = request.getHeader(Const.AUTHORIZATION);
        if (jwt != null) {
            stringRedisTemplate.delete("token_" + jwt);
        }

        String token = TokenUtils.createJwtToken("user", user);
        ObjectMapper om = new ObjectMapper();
        String value = null;
        try {
            value = om.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        stringRedisTemplate.boundValueOps("token_" + token).set(value);
        stringRedisTemplate.boundValueOps("token_" + token).expire(4, TimeUnit.MINUTES);

        return R.createSuccess("登录成功", token);
    }

    @Override
    public R searchBalance(String userId) {
        Account account = accountMapper.selectById(userId);
        if (account == null) {
            return R.createFAIL("用户信息不存在");
        }
        return R.createSuccess(account.getBalance());
    }

    @Override
    public R updatePassword(HttpServletRequest request, UpdatePasswordInputVo inputVo) {
        if (!inputVo.getNewPassword1().equals(inputVo.getNewPassword2())) {
            return R.createFAIL("两次输入的密码不一致");
        }

        String jwt = request.getHeader(Const.AUTHORIZATION);
        String str = stringRedisTemplate.boundValueOps("token_" + jwt).get();
        Account account = null;
        try {
            account = new ObjectMapper().readValue(str, Account.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        if (!account.getPassword().equals(inputVo.getPassword() + "")) {
            return R.createFAIL("密码输入有误");
        }
        account.setPassword(inputVo.getNewPassword1() + "");
        int i = accountMapper.updateById(account);

        if (i <= 0) {
            return R.createFAIL("密码修改失败");
        }

        Boolean delete = stringRedisTemplate.delete("token_" + jwt);
        if (!delete) {
            return R.createFAIL("修改密码服务出现了异常");
        }
        return R.createSuccess("密码修改成功");
    }

    @Override
    public R logout(HttpServletRequest request) {
        String jwt = request.getHeader(Const.AUTHORIZATION);

        Boolean delete = stringRedisTemplate.delete("token_" + jwt);

        if (delete) {
            return R.createSuccess("退出登录");
        }

        return R.createFAIL("退出失败");
    }

}
